<template>
    <!--  弃用！虽然可以动态生成表单，但是对数据校验不友好-->
    <!--    可以考虑整合 VeeValidate-->
    <div class="el-form-generator">
        <el-form :model="comnFormValue" status-icon :rules="rules" ref="comnForm" label-width="50px" class="comnForm">

            <el-form-item v-for="formItem in formItems" :label="formItem.label" :prop="formItem.prop"
                          :key="formItem.key">
                <el-input :type="formItem.type" v-model="formItem.value" autocomplete="off"></el-input>
            </el-form-item>

            <span v-show="false">
                <el-form-item>
                    <el-button type="primary" @click="submitForm('comnForm')">提 交</el-button>
                </el-form-item>
            </span>
        </el-form>
    </div>
</template>

<script>


import commonValidateRules from "@/assets/utils/elFormValidate"

export default {
    name: "ElFormGenerator",
    data() {
        return {
            formItems: [
                {
                    key: '001',
                    label: "邮箱",
                    prop: "email",
                    type: "email",
                    name: "email",
                    value: "karl@B.co"
                },
                {
                    key: '002',
                    label: "密码",
                    prop: "pass",
                    type: "password",
                    name: "password",
                    value: "karl"
                }
            ],
            rules: commonValidateRules
        }
    },
    methods: {
        submitForm() {
            console.log("点击了通用Form的提交按钮！")
            console.log(JSON.stringify(this.comnFormValue))
        },
        getFormJSON() {
            this.validateFormAll();
            return JSON.stringify(this.comnFormValue)
        },
        async validateFormAll() {
            console.log("进入form校验")
            let result = await this.$refs.comnForm.validate();
            return result
        }
    },
    computed: {
        comnFormValue: function () {

            // 从表单的结构提取出数据的键值对
            let formValue = {};
            for (let i = 0; i < this.formItems.length; i++) {

                let name = this.formItems[i].name;
                let temp = {
                    [name]: this.formItems[i].value
                };

                Object.assign(formValue, temp)
            }

            return formValue;
        }
    }
}
</script>

<style scoped>

</style>
